// ==UserScript==
// @name         walmart补充信息
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @updateURL    https://gitee.com/great-pacey/tampermonkey/raw/master/additional .user.js
// @match        https://www.walmart.com/*
// @require      https://code.jquery.com/jquery-3.6.0.min.js
// @icon         https://www.google.com/s2/favicons?sz=64&domain=walmart.com
// @grant        unsafeWindow
// @grant        GM_registerMenuCommand
// ==/UserScript==
/** global $ */

(function() {
    'use strict';
    GM_registerMenuCommand("看类目", log)
    $(main);

    function main() {
        let count;
        try {
            count = unsafeWindow.__NEXT_DATA__.props.pageProps.initialData.searchResult.itemStacks[0].meta.totalItemCount;
            insertEl(count);
        } catch(err) {
            console.log(err)
        }
    }

    function formatNum(number) {
        let arr = String(number).split('.');
        let num = arr[0];
        let len = Math.ceil(num.length / 3) * 3;
        let result = num.padStart(len, '0').match(/\d{3}/g).join(',').replace(/^0+/, '');
        return arr[1] ? result + '.' + arr[1] : result;
    }

    function insertEl(num) {
        const header = document.querySelector('header');
        const span = document.createElement("span");
        span.innerText = formatNum(num);
        setStyle(span);
        header.appendChild(span);
    }

    function setStyle(el) {
        el.style.color = 'white'
        el.style.position = 'absolute'
        el.style.left = 0
        el.style.top = 0
    }

    function log() {
        console.log("类目分数", unsafeWindow.__NEXT_DATA__.props.pageProps.initialData.pageMetadata.pageContext.searchNormalize.product_type)
    }
})();